<template>
  <div class="p-6 max-w-4xl mx-auto">
    <h2 class="text-2xl font-bold mb-6">📝 博客管理后台</h2>

    <el-button type="primary" @click="openAddDialog" class="mb-4"
      >新增文章</el-button
    >
    <el-button type="success" @click="goBack">返回</el-button>

    <el-table
      v-loading="loading"
      :data="blogs"
      border
      stripe
      class="mb-6"
      style="width: 100%"
    >
      <el-table-column prop="title" label="标题" />
      <el-table-column label="发布时间" width="180">
        <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="更新时间" width="180">
        <template #default="{ row }">{{ formatDate(row.updateTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editArticle(row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="deleteArticle(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEditing ? '编辑文章' : '新增文章'"
      v-model="showAdd"
      width="800px"
      :destroy-on-close="false"
    >
      <el-form :model="form" label-width="70px">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.summary" />
        </el-form-item>
        <el-form-item label="内容">
          <v-md-editor v-model="form.content" height="300px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAdd = false" :disabled="submitting"
          >取消</el-button
        >
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import VMdEditor from "@kangc/v-md-editor";
import {
  createBlog,
  updateBlog,
  deleteBlogById,
  fetchBlogList,
} from "../api/blogAdmin";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const blogs = ref([]);
const showAdd = ref(false);
const isEditing = ref(false);
const loading = ref(false);
const submitting = ref(false);

const form = reactive({
  id: 0,
  title: "",
  summary: "",
  content: "",
  createTime: "",
  updateTime: "",
});
const fetchBlogs = async () => {
  loading.value = true;
  try {
    const res = await fetchBlogList();
    if (res.code === 200) blogs.value = res.data || [];
  } catch (err) {
    console.error("获取博客列表失败", err);
  } finally {
    loading.value = false;
  }
};

onMounted(fetchBlogs);

const goBack = () => router.back();

const openAddDialog = () => {
  resetForm();
  isEditing.value = false;
  showAdd.value = true;
};

const submitForm = async () => {
  if (!form.title.trim() || !form.summary.trim() || !form.content.trim()) {
    ElMessage.warning("请填写完整内容");
    return;
  }

  const payload = {
    id: form.id,
    title: form.title,
    summary: form.summary,
    content: form.content,
  };

  submitting.value = true;
  try {
    const res = isEditing.value
      ? await updateBlog(payload)
      : await createBlog(payload);
    if (res.code === 200) {
      ElMessage.success("操作成功");
      showAdd.value = false;
      resetForm();
      fetchBlogs();
    } else {
      ElMessage.error(res.message || "操作失败");
    }
  } catch (err) {
    console.error("提交失败", err);
    ElMessage.error("网络错误，请稍后重试");
  } finally {
    submitting.value = false;
  }
};

const editArticle = (blog) => {
  Object.assign(form, {
    id: blog.id,
    title: blog.title,
    summary: blog.summary,
    content: blog.content,
    createTime: blog.createTime,
    updateTime: blog.updateTime,
  });
  isEditing.value = true;
  showAdd.value = true;
};

const deleteArticle = async (blog) => {
  try {
    await ElMessageBox.confirm("确认删除这篇文章吗？", "提示", {
      type: "warning",
    });
    await deleteBlogById(blog.id);
    ElMessage.success("删除成功");
    fetchBlogs();
  } catch (err) {
    if (err !== "cancel") {
      console.error("删除失败", err);
      ElMessage.error("删除失败");
    }
  }
};

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    title: "",
    summary: "",
    content: "",
    createTime: "",
    updateTime: "",
  });
};

const formatDate = (isoStr) => {
  if (!isoStr) return "";
  const d = new Date(isoStr);
  return d.toLocaleDateString() + " " + d.toLocaleTimeString();
};
</script>

<style scoped>
/* 可选样式优化 */
</style>
